package com.ocean.redflagtest.mvvm.models.repositorys;



import android.app.Application;
import android.arch.lifecycle.LiveData;
import android.os.Handler;
import android.os.Message;

import com.ocean.redflagtest.mvvm.base.BaseRepository;
import com.ocean.redflagtest.mvvm.callback.OnRedFlagCallBack;
import com.ocean.redflagtest.mvvm.models.entity.OriginalModel;
import com.ocean.redflagtest.mvvm.models.sql.OriginalModelDao;
import com.ocean.redflagtest.mvvm.models.sql.OriginalRoomDatabase;
import com.ocean.redflagtest.utils.AppExecutors;
import com.ocean.redflagtest.utils.OceanUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by ocean on 2018/8/2
 * Author :  ocean
 * Email  :  348686686@qq.com
 */
public class MainRepository extends BaseRepository<OriginalModelDao, List<OriginalModel>> {

    private List<OriginalModel> mOriginalModels = null;
    private OnRedFlagCallBack<List<OriginalModel>> mOnRedFlagCallBack = null;

    /**
     * resolve room cannot access ui thread
     */
    private AppExecutors executors = new AppExecutors();

    public void setmOnRedFlagCallBack(OnRedFlagCallBack<List<OriginalModel>> mOnRedFlagCallBack) {
        this.mOnRedFlagCallBack = mOnRedFlagCallBack;
    }

    public MainRepository(Application application) {
        OriginalRoomDatabase db = OriginalRoomDatabase.Companion.getINSTANCE(application);
        dao = db.originalModelDao();
//        if (dao == null){
//            OceanUtils.logE("111111111111");
//        }else {
//            OceanUtils.logE("2222222222222");
//        }
    }


    @Override
    public List<OriginalModel> getData() {
        LiveData<List<OriginalModel>> liveData = dao.getAllOriginals();
        List<OriginalModel> originalModelList = liveData.getValue();
        if (mOriginalModels == null) {
            mOriginalModels = new ArrayList<>();
            if (originalModelList != null
                    && !originalModelList.isEmpty()) {
                mOriginalModels = originalModelList;
            }
        }

        OceanUtils.HttpGet("https://s.jshqpp.com/api/test.php", new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 200) {
                    String result = (String) msg.obj;
                    final List<OriginalModel> list = OceanUtils.getOriginalList(result);
                    executors.getDiskIO().execute(new Runnable() {
                        @Override
                        public void run() {
                            dao.deleteAll();
                            dao.insertAll(list);
                        }
                    });
                    mOriginalModels = list;
                    if (mOnRedFlagCallBack != null) {
                        mOnRedFlagCallBack.onChanged(mOriginalModels);
                    }
                }
            }
        });

        return mOriginalModels;
    }

}
